from Day14.nico import union_lotto
import sys
import os


class UnionLotto():
    def __init__(self):
        self._filename = 'data.txt'
        self._pools = []
        self._saved = True
        self._load_local_data()

    @property
    def pools(self):
        return self._pools

    def manual_bet(self, balls=None):
        if balls:
            self._pools.append(balls)
        tmp = self._get_manual_bet()
        if tmp:
            self._pools.append()
        self._saved = False

    def _get_manual_bet(self):
        balls = input('请输入一注双色球,逗号分隔\n')
        if self._check_balls(balls):
            return balls
        else:
            print('双色球输入有误,请重新输入')

    def random_bet(self):
        self._pools.extend(union_lotto())
        self._saved = False
        print('下注成功')

    def save(self):
        with open(self._filename, 'w+') as f:
            f.write('\n'.join(self._pools))
        self._saved = True
        print('保存成功')

    def edit(self):
        number = int(input('请输入需要修改的双色球编号'))
        if int(number) > len(self._pools):
            print('编号输入超出范围')
            self.edit()
        else:
            self._pools[number - 1] = self._get_manual_bet()
        self._saved = False

    def clear(self):
        self._pools.clear()
        self._saved = False
        print('清空成功')

    def exit(self):
        if not self._saved or self._pools:
            select = input('您还有数据未保存，是否保存数据，是请按y键，否请任意键并回车。\n')
            if select == 'y':
                self.save()
        sys.exit()

    def _load_local_data(self):
        if not os.path.exists(self._filename):
            with open(self._filename, 'w') as f:
                pass
        with open(self._filename, 'r') as f:
            self._pools.extend([i.strip() for i in f.readlines()])
        print(f'读取本地数据成功:{self._pools}')

    def _check_balls(self, balls):
        bp = balls.split(',')
        if len(bp) == 7 and all([i.isdigit() for i in bp]):
            return True
        return False


if __name__ == '__main__':
    try:
        u = UnionLotto()
        options = {'a': u.manual_bet, 'b': u.random_bet, 'c': u.edit, 'd': u.clear, 'e': u.save, 'f': u.exit}
        while True:
            select = input('a.手输一注\tb.机选一注\tc.编辑\td.清空\te.存档\tf.退出\n')
            if select not in options:
                print('选择有误,请重新选择~')
                continue
            options[select]()
            print(f'当前下注:{u.pools}')
    except Exception as e:
        print('系统异常', e)
